<template>
  <div class="detail-comment">
    <div class="add-area">
      <div class="avg-score-container">
        <div class="label">综合评价</div>
        <div class="stars-wrapper">
          <i
            v-for="(item, index) in 5"
            :key="'avg-empty-' + index"
            class="empty-star"
            :style="{
              background: `url(${EmptyStar}) center center / contain no-repeat`
            }"
          ></i>
          <i
            v-for="(item, index) in Number.parseInt(avgScore / 2)"
            :key="'avg-full-' + index"
            class="avg-star"
            :style="{
              background: `url(${FullStar}) center center / contain no-repeat`
            }"
          ></i>
          <i
            class="avg-star"
            :style="{
              background: `url(${FullStar}) left center / 24px 24px no-repeat`,
              width: `${((avgScore / 2) - Number.parseInt(avgScore / 2)) * 24}px`
            }"
          ></i>
        </div>
        <i class="avg-score">{{ Number.parseFloat(avgScore).toFixed(1) }}</i>
      </div>
      <div class="my-score-container" ref="scoreContainer">
        <div class="label">我的评价</div>
        <div class="stars-wrapper" ref="myComment">
          <i
            v-for="(item, index) in 5"
            :key="'my-empty-' + index"
            class="empty-star"
            :style="{
              background: `url(${EmptyStar}) center center / contain no-repeat`
            }"
          ></i>
          <i
            v-for="(item, index) in Number.parseInt(myScore / 2)"
            :key="'my-full-' + index"
            class="my-star"
            :style="{
              background: `url(${FullStar}) center center / contain no-repeat`
            }"
          ></i>
          <i
            class="my-star"
            :style="{
              background: `url(${FullStar}) left center / 24px 24px no-repeat`,
              width: `${((myScore / 2) - Number.parseInt(myScore / 2)) * 24}px`
            }"
          ></i>
        </div>
        <i class="my-score">{{ myScore.toFixed(1) }}</i>
      </div>
      <div class="content-wrapper">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="添加你的评论吧..."
          resize="none"
          v-model="content">
        </el-input>
      </div>
      <div class="operation-container">
        <span
          class="cancel"
          @click="content = '', myScore = 0"
        >清空</span>
        <span
          class="summit"
          @click="handleSummit"
        >发表</span>
      </div>
    </div>
    <div class="show-area">
      <div
        class="card"
        v-for="comment in commentData"
        :key="comment.comment_id"
      >
        <div class="card-upper">
          <div class="col-left">
            <span class="avatar"></span>
          </div>
          <div class="col-right">
            <span class="username">{{ comment.username }}</span>
            <span class="score">
              <div class="stars-wrapper">
                <i
                  v-for="(item, index) in 5"
                  :key="comment.comment_id + 'comment-empty-' + index"
                  class="comment-empty-star"
                  :style="{
                    background: `url(${EmptyStar}) center center / contain no-repeat`
                  }"
                ></i>
                <i
                  v-for="(item, index) in Number.parseInt(comment.score / 2)"
                  :key="comment.comment_id + 'my-full-' + index"
                  class="comment-star"
                  :style="{
                    background: `url(${FullStar}) center center / contain no-repeat`
                  }"
                ></i>
                <i
                  class="comment-star"
                  :style="{
                    background: `url(${FullStar}) left center / 16px 16px no-repeat`,
                    width: `${((comment.score / 2) - Number.parseInt(comment.score / 2)) * 16}px`
                  }"
                ></i>
              </div>
              <i class="comment-score">{{ comment.score.toFixed(1) }}</i>
            </span>
          </div>
        </div>
        <div class="card-bottom">
          {{ comment.content }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import EmptyStar from './images/icon-star-empty.svg'
import HalfStar from './images/icon-star-half.svg'
import FullStar from './images/icon-star-full.svg'
import { addComment, getComment } from '@/network/detail'
export default {
  name: 'DetailComment',
  props: {
    commentData: [Array, Object]
  },
  data () {
    return {
      content: '',
      user_id: window.localStorage.getItem('user_id'),
      app_id: this.$route.params.id,
      avgScore: 0,
      EmptyStar,
      HalfStar,
      FullStar,
      myScore: 0,
      // 用户是否点击星星确认评分
      isComfirm: false
    }
  },
  created () {
    this.calAvgScore()
  },
  mounted () {
    this.$refs['myComment'].addEventListener('mouseenter', this.bindMousemove)
    this.$refs['myComment'].addEventListener('mouseleave', this.clearMyScore)
    this.$refs['myComment'].addEventListener('click', this.confirmMyScore)
  },
  methods: {
    // 计算平均分
    calAvgScore () {
      if (!(this.commentData instanceof Array) || this.commentData.length === 0) return
      let total = 0
      this.commentData.forEach(item => {
        total += Number.parseFloat(item.score)
      })
      if (total > 0) {
        this.avgScore = Number.parseFloat(total / this.commentData.length).toFixed(2)
      }
    },
    // mouseenter 时绑定 mouseover 事件
    bindMousemove () {
      this.isComfirm = false
      this.$refs['myComment'].addEventListener('mousemove', this.setMyScore)
    },
    // 解绑 mouseover
    unbindMousemove () {
      this.$refs['myComment'].removeEventListener('mousemove', this.setMyScore)
    },
    // mousemove 时设置星星和评分
    setMyScore (e) {
      const curPositionX = e.x - this.$refs['myComment'].getBoundingClientRect().left
      const firstScore = Number.parseInt(curPositionX / 12)
      const restPX = curPositionX - firstScore * 12
      if (restPX >= 6) {
        this.myScore = firstScore + 1
      } else {
        this.myScore = firstScore
      }
    },
    // mouseout 时清空评分
    clearMyScore () {
      console.log('mouseout')
      if (this.isComfirm) return
      this.myScore = 0
    },
    // click 时确定评分并移除 mouseover 事件
    confirmMyScore () {
      this.isComfirm = true
      this.unbindMousemove()
    },
    // 上传评论
    async handleSummit () {
      if (!this.content.trim()) {
        this.$message({
          type: 'warning',
          message: '评论内容不能为空！'
        })
        return
      }
      const { data, code } = await addComment({
        content: this.content.trim(),
        score: this.myScore,
        user_id: this.user_id,
        app_id: this.app_id
      })
      if (code === 200) {
        this.$message({
          type: 'success',
          message: '发表成功！'
        })
        this.content = ''
        this.myScore = 0
        this.$emit('reloadComment')
      } else {
        this.$message({
          type: 'error',
          message: '操作失败！请联系管理员！'
        })
      }
    }
  },
  watch: {
    commentData () {
      this.calAvgScore()
    }
  }
}
</script>

<style lang="scss" scoped>
  $lightColor: #ccc;
  $darkColor: #999;
  $themeColor: #15C5CE;
  .detail-comment {
    display: flex;
    flex-direction: column;
    .add-area {
      display: flex;
      flex-direction: column;
      .avg-score-container {
        display: flex;
        height: 45px;
        align-items: center;
        .label {
          color: $lightColor;
          margin-right: 10px;
        }
        .stars-wrapper {
          display: flex;
          position: relative;
          .empty-star {
            width: 24px;
            height: 24px;
            cursor: pointer;
          }
          .avg-star {
            position: absolute;
            top: 0;
            z-index: 1;
            width: 24px;
            height: 24px;
            cursor: pointer;
            &:nth-of-type(5n + 1) {
              left: 0;
            }
            &:nth-of-type(5n + 2) {
              left: 24px;
            }
            &:nth-of-type(5n + 3) {
              left: 48px;
            }
            &:nth-of-type(5n + 4) {
              left: 72px;
            }
            &:nth-of-type(5n + 5) {
              left: 96px;
            }
          }
        }
        .avg-score {
          font-style: normal;
          color: $themeColor;
          font-weight: bold;
          font-size: 24px;
          line-height: 24px;
          margin-left: 10px;
        }
      }
      .my-score-container {
        display: flex;
        height: 45px;
        align-items: center;
        .label {
          color: $lightColor;
          margin-right: 10px;
        }
        .stars-wrapper {
          display: flex;
          position: relative;
          .empty-star {
            width: 24px;
            height: 24px;
            cursor: pointer;
          }
          .my-star {
            position: absolute;
            top: 0;
            z-index: 1;
            width: 24px;
            height: 24px;
            cursor: pointer;
            &:nth-of-type(5n + 1) {
              left: 0;
            }
            &:nth-of-type(5n + 2) {
              left: 24px;
            }
            &:nth-of-type(5n + 3) {
              left: 48px;
            }
            &:nth-of-type(5n + 4) {
              left: 72px;
            }
            &:nth-of-type(5n + 5) {
              left: 96px;
            }
          }
        }
        .my-score {
          font-style: normal;
          color: $themeColor;
          font-weight: bold;
          font-size: 24px;
          line-height: 24px;
          margin-left: 10px;
        }
      }
      .content-wrapper {
        padding-top: 10px;
        ::v-deep .el-textarea__inner {
          font-size: 16px;
          color: $darkColor;
        }
      }
      .operation-container {
        display: flex;
        justify-content: flex-end;
        padding-top: 10px;
        .cancel {
          margin-right: 10px;
          color: $lightColor;
          line-height: 30px;
          cursor: pointer;
          &:hover {
            color: $darkColor;
          }
        }
        .summit {
          position: relative;
          width: 60px;
          height: 30px;
          background-color: $themeColor;
          color: #fff;
          line-height: 30px;
          text-align: center;
          border-radius: 4px;
          cursor: pointer;
          &:hover {
            &::before {
              position: absolute;
              top: 0;
              left: 0;
              width: 100%;
              height: 100%;
              background-color: rgba($color: #fff, $alpha: .2);
              content: "";
            }
          }
        }
      }
    }
    .show-area {
      .card {
        background-color: #fff;
        margin: 10px 0;
        border-radius: 10px;
        padding: 16px;
        .card-upper {
          display: flex;
          align-items: center;
          height: 60px;
          border-bottom: 1px solid rgba($color: $lightColor, $alpha: .6);
          .col-left {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            .avatar {
              height: 44px;
              width: 44px;
              margin-right: 6px;
              border-radius: 22px;
              background: url(./images/image-default-avatar.jpg) center center / cover no-repeat;
            }
          }
          .col-right {
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 100%;
            line-height: 22px;
            .username {
              color: $darkColor;
            }
            .score {
              display: flex;
              justify-content: center;
              align-items: center;
              .stars-wrapper {
                position: relative;
                display: flex;
                width: 80px;
                margin-right: 8px;
                .comment-empty-star {
                  width: 16px;
                  height: 16px;
                }
                .comment-star {
                  position: absolute;
                  width: 16px;
                  height: 16px;
                &:nth-of-type(5n + 1) {
                  left: 0;
                }
                &:nth-of-type(5n + 2) {
                  left: 16px;
                }
                &:nth-of-type(5n + 3) {
                  left: 32px;
                }
                &:nth-of-type(5n + 4) {
                  left: 48px;
                }
                &:nth-of-type(5n + 5) {
                  left: 64px;
                }
                }
              }
              .comment-score {
                color: $lightColor;
                font-size: 14px;
                font-style: normal;
              }
            }
          }
        }
        .card-bottom {
          min-height: 60px;
          padding-top: 16px;
          color: $darkColor;
        }
      }
    }
  }
</style>